package com.wzxy.parse.wx;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wzxy.common.Const;
import com.wzxy.spider.wx.entity.Topic;
import com.wzxy.spider.wx.service.impl.TopicService;
import com.wzxy.util.MyTimeUtils;
import com.wzxy.wzinfo.entiry.NewsIntroduce;
import com.wzxy.wzinfo.service.impl.NewsIntService;

/**
 * 解析分享文章
 * 
 * @author h
 * 
 */
@Service
public class WxShareArticle {
	
	@Autowired
	private NewsIntService newsIntService;	
	@Autowired
	private TopicService topicService;

	public void startParse(Topic toptic) {

		if (StringUtils.isNotBlank(toptic.getHtml())) {

			Document doc = Jsoup.parse(toptic.getHtml());
			NewsIntroduce introduce = new NewsIntroduce();

			String nickname = doc.select("[id=post-user]").text();
			System.out.println("用户：" + nickname);

			String shareDate = doc.select("[id=publish_time]").text();
			System.out.println("分享日期：" + shareDate);

			String author = doc.select("[id=js_share_author]").text();
			introduce.setSource(Const.WX + author);
			System.out.println("原文作者：" + author);

			String title = toptic.getTitle();
			if(StringUtils.isBlank(title)){
				title = doc.title();
			}
			introduce.setTitle(title);
			System.out.println("文章的标题：" + title);

			String originSite = toptic.getUrl();
			if(StringUtils.isBlank(originSite)){
				originSite = doc.select("[id=js_share_source]").attr("href");
			}
			introduce.setURL(originSite);
			System.out.println("原文链接：" + originSite);

			String site = doc.select("[id=post-user]").text();
			System.out.println("来源网站：" + site);

			String content = doc.select("script").select("[id=content_tpl]").html();
			introduce.setContent(getSummary(content));
			System.out.println("摘要：" + getSummary(content));
			
			String parseTime = MyTimeUtils.getNowDateString();
			introduce.setCreationTime(parseTime);
			System.out.println("解析时间：" + parseTime);
			
			newsIntService.save(introduce);
			toptic.setStatus(com.wzxy.common.Const.DONE);
			topicService.update(toptic, toptic.getId());
		}
	}

	/**
	 * 获取摘要步骤： 1、通过 <script> 标签获取 HTML 片段 2、解析 HTML 获取文本
	 * 
	 * @param summaryHtml
	 * @return
	 */
	public String getSummary(String summaryHtml) {
		Document doc = Jsoup.parse(summaryHtml);
		return doc.text();
	}

}
